// 引入常态化样式
require("../../assets/css/normalize.css");
//引入重置样式
require("../../assets/css/reset.css");
// 引入公共样式
require("../../assets/css/common.css");
// 引入阿里矢量图
require("../../assets/fonts/iconfont.css");
// 引入自己的样式
require("./sport_course_play.less");
//引入公共js
const dom = require("../../utils/dom.js");
const axios = require("../../utils/axios.js");
document.addEventListener("DOMContentLoaded", function () {
	// 1.读取数据
	const fragments = JSON.parse(localStorage.getItem("fragments"));
	// 2.渲染数据
	let video = dom.get("#video");
	let n = 0;
	// 获取进入页面的时间
	let startTime = Date.now();
	// 运动持续时间
	let duration = 0;
	// 3.播放视频
	function play() {
		video.src = axios.defaults.baseURL + fragments[n].videoUrl;
		dom.get("#part").textContent = n + 1;
		dom.get("#totalPart").textContent = fragments.length;
		dom.get("#title").textContent = fragments[n].title;
		video.play();
		let timer = window.setInterval(function () {
			dom.get(".progress-width").style.width =
				(100 * video.currentTime) / video.duration + "%";
		}, 25);
	}
	play();
	// 4.播放结束自动播放下一节
	video.addEventListener("ended", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1;
		}
	});
	// 5.点击按钮播放上一节
	dom.get(".icon-retreat").addEventListener("click", function () {
		n--;
		if (n < 0) {
			n = 0;
		}
		play();
	});
	// 6.点击按钮播放下一节
	dom.get(".icon-advance").addEventListener("click", function () {
		n++;
		if (n >= fragments.length) {
			n = fragments.length - 1;
		} else {
			play();
		}
	});
	// 7.点击暂停按钮显示蒙层
	dom.get(".icon-pause2").addEventListener("click", function () {
		dom.get("#mask").style.display = "block";
		dom.get("#maskBtn").style.display = "flex";
		dom.get(".slogn").style.display = "block";
		video.pause();
		// 持续时间
		duration += Date.now() - startTime;
	});
	// 8.点击继续按钮隐藏蒙层
	dom.get(".continue-btn").addEventListener("click", function () {
		dom.get("#mask").style.display = "none";
		dom.get("#maskBtn").style.display = "none";
		dom.get(".slogn").style.display = "none";
		video.play();
		startTime = Date.now();
	});
	// 9.点击蒙层让自己消失，视频暂停
	dom.get("#mask").addEventListener("click", function () {
		this.style.display = "none";
		dom.get(".slogn").style.display = "none";
		dom.get("#maskBtn").style.display = "none";
		video.play();
	});
	// 10.点击结束，结束训练并发送请求
	dom.get(".pause-btn").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = duration * 2;
		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("再见");
					location.href = "sport_course.html";
				}
			});
	});
});
